package com.ecommerce.order.service.impl;

import com.ecommerce.order.client.UserServiceClient;
import com.ecommerce.order.dto.OrderCreateRequest;
import com.ecommerce.order.dto.OrderItemResponse;
import com.ecommerce.order.dto.OrderResponse;
import com.ecommerce.order.dto.OrderStatsResponse;
import com.ecommerce.order.dto.OrderUpdateStatusRequest;
import com.ecommerce.order.dto.OrderPageResponse;
import com.ecommerce.order.entity.Order;
import com.ecommerce.order.entity.OrderItem;
import com.ecommerce.order.repository.OrderRepository;
import com.ecommerce.order.repository.OrderItemRepository;
import com.ecommerce.order.service.OrderService;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
@Service
public class OrderServiceImpl implements OrderService {

    @Autowired
    private OrderRepository orderRepository;

    @Autowired
    private OrderItemRepository orderItemRepository;

    @Autowired
    private UserServiceClient userServiceClient;

    @Override
    @Transactional
    public OrderResponse createOrder(OrderCreateRequest createRequest, Long userId, String username) {
        log.info("创建订单请求: {}", createRequest);

        try {
            // 确定最终的收货信息
            String finalReceiverName = createRequest.getReceiverName();
            String finalReceiverPhone = createRequest.getReceiverPhone();
            String finalReceiverAddress = createRequest.getReceiverAddress();

            // 尝试调用用户服务获取用户信息，如果失败则使用请求中的信息
            try {
                // 调用用户服务获取用户信息
                log.info("调用用户服务获取用户信息，用户ID: {}", userId);
                
                // 获取当前用户的token
                String token = getCurrentToken();
                String authorizationHeader = token.isEmpty() ? "" : "Bearer " + token;
                
                // 调用用户服务获取用户信息
                String userInfoJson = userServiceClient.getUserById(userId, authorizationHeader);
                
                log.info("用户服务返回: {}", userInfoJson);
                ObjectMapper objectMapper = new ObjectMapper();
                JsonNode userInfo = objectMapper.readTree(userInfoJson);
                
                // 获取用户真实信息
                String realName = getJsonNodeText(userInfo, "nickName");
                if (realName == null || realName.trim().isEmpty()) {
                    realName = getJsonNodeText(userInfo, "username");
                }
                String realPhone = getJsonNodeText(userInfo, "phone");
                String realAddress = getJsonNodeText(userInfo, "address");

                // 如果收货信息为空或者是测试数据，使用用户真实信息
                if (finalReceiverName == null || finalReceiverName.trim().isEmpty() || 
                    "张三".equals(finalReceiverName) || "测试用户".equals(finalReceiverName)) {
                    finalReceiverName = realName;
                }
                
                if (finalReceiverPhone == null || finalReceiverPhone.trim().isEmpty() || 
                    "13800138000".equals(finalReceiverPhone)) {
                    finalReceiverPhone = realPhone;
                }
                
                if (finalReceiverAddress == null || finalReceiverAddress.trim().isEmpty() || 
                    "测试地址".equals(finalReceiverAddress)) {
                    finalReceiverAddress = realAddress;
                }
                
                log.info("使用用户服务信息 - 姓名: {}, 电话: {}, 地址: {}", 
                        finalReceiverName, finalReceiverPhone, finalReceiverAddress);
                        
            } catch (Exception e) {
                log.warn("调用用户服务失败，使用请求中的收货信息: {}", e.getMessage());
                // 如果用户服务不可用，确保收货信息不为空
                if (finalReceiverName == null || finalReceiverName.trim().isEmpty()) {
                    finalReceiverName = "默认用户";
                }
                if (finalReceiverPhone == null || finalReceiverPhone.trim().isEmpty()) {
                    finalReceiverPhone = "13800138000";
                }
                if (finalReceiverAddress == null || finalReceiverAddress.trim().isEmpty()) {
                    finalReceiverAddress = "默认地址";
                }
            }
            
            // 创建最终变量用于lambda表达式
            final String receiverName = finalReceiverName;
            final String receiverPhone = finalReceiverPhone;
            final String receiverAddress = finalReceiverAddress;

            log.info("使用收货信息 - 姓名: {}, 电话: {}, 地址: {}", 
                    finalReceiverName, finalReceiverPhone, finalReceiverAddress);

            // 创建订单实体
            Order order = new Order();
            order.setUserId(userId);
            order.setUsername(username);
            order.setReceiverName(receiverName);
            order.setReceiverPhone(receiverPhone);
            order.setReceiverAddress(receiverAddress);
            order.setRemark(createRequest.getRemark());
            
            // 计算总金额
            BigDecimal totalAmount = createRequest.getItems().stream()
                    .map(item -> item.getPrice().multiply(BigDecimal.valueOf(item.getQuantity())))
                    .reduce(BigDecimal.ZERO, BigDecimal::add);
            
            order.setTotalAmount(totalAmount);
            order.setShippingFee(BigDecimal.ZERO); // 默认运费为0
            order.setPayAmount(totalAmount); // 实付金额等于总金额
            order.setStatus(0); // 0-待付款
            
            // 生成订单编号
            String orderNo = generateOrderNo();
            order.setOrderNo(orderNo);

            // 保存订单
            order = orderRepository.save(order);
            log.info("订单保存成功，订单ID: {}", order.getId());

            // 创建final变量用于lambda表达式
            final Long finalOrderId = order.getId();

            // 保存订单项
            List<OrderItem> orderItems = createRequest.getItems().stream()
                    .map(itemDTO -> {
                        OrderItem item = new OrderItem();
                        item.setOrderId(finalOrderId);
                        item.setProductId(itemDTO.getProductId());
                        item.setProductName("商品" + itemDTO.getProductId()); // 临时使用，实际应该从商品服务获取
                        item.setProductImage(""); // 临时使用，实际应该从商品服务获取
                        item.setProductPrice(itemDTO.getPrice());
                        item.setQuantity(itemDTO.getQuantity());
                        item.setSubtotal(itemDTO.getPrice().multiply(BigDecimal.valueOf(itemDTO.getQuantity())));
                        return item;
                    })
                    .collect(Collectors.toList());

            orderItemRepository.saveAll(orderItems);
            log.info("订单项保存成功，共 {} 项", orderItems.size());

            // 构建响应
            return convertToResponse(order, orderItems);

        } catch (Exception e) {
            log.error("创建订单失败: {}", e.getMessage(), e);
            throw new RuntimeException("创建订单失败: " + e.getMessage());
        }
    }

    @Override
    public OrderResponse getOrderById(Long orderId, Long userId) {
        log.info("查询订单详情 - 订单ID: {}, 用户ID: {}", orderId, userId);
        
        Order order = orderRepository.findById(orderId)
                .orElseThrow(() -> new RuntimeException("订单不存在"));
        
        // 验证订单是否属于该用户
        if (!order.getUserId().equals(userId)) {
            log.warn("订单不属于该用户 - 订单ID: {}, 用户ID: {}, 订单用户ID: {}", 
                    orderId, userId, order.getUserId());
            throw new RuntimeException("订单不存在");
        }
        
        // 获取订单项
        List<OrderItem> orderItems = orderItemRepository.findByOrderId(orderId);
        
        log.info("订单查询成功 - 订单ID: {}", orderId);
        return convertToResponse(order, orderItems);
    }

    @Override
    public OrderResponse getByOrderNo(String orderNo, Long userId) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public OrderPageResponse getOrdersByUserId(Long userId, Integer page, Integer size) {
        log.info("获取用户订单列表 - 用户ID: {}, 页码: {}, 大小: {}", userId, page, size);
        
        try {
            // 创建分页参数
            Pageable pageable = PageRequest.of(page, size, Sort.by(Sort.Direction.DESC, "createdAt"));
            
            // 查询订单分页数据
            Page<Order> orderPage = orderRepository.findByUserId(userId, pageable);
            
            log.info("查询结果 - 总订单数: {}, 当前页订单数: {}", orderPage.getTotalElements(), orderPage.getContent().size());
            
            // 构建响应
            OrderPageResponse response = new OrderPageResponse();
            List<OrderResponse> orders = new ArrayList<>();
            
            // 转换订单数据
            log.info("开始转换订单数据，当前页订单数量: {}", orderPage.getContent().size());
            for (Order order : orderPage.getContent()) {
                log.info("处理订单 - ID: {}, 订单号: {}, 用户ID: {}", order.getId(), order.getOrderNo(), order.getUserId());
                try {
                    List<OrderItem> orderItems = orderItemRepository.findByOrderId(order.getId());
                    log.info("订单项数量: {}", orderItems.size());
                    OrderResponse orderResponse = convertToResponse(order, orderItems);
                    log.info("转换后的订单响应: {}", orderResponse);
                    orders.add(orderResponse);
                    log.info("成功添加订单到列表，当前列表大小: {}", orders.size());
                } catch (Exception e) {
                    log.error("转换订单失败 - 订单ID: {}, 错误: {}", order.getId(), e.getMessage(), e);
                    // 继续处理其他订单，而不是完全失败
                }
            }
            log.info("转换完成，订单列表大小: {}", orders.size());
            
            response.setOrders(orders);
            response.setTotal(orderPage.getTotalElements());
            response.setPage(page);
            response.setSize(size);
            response.setTotalPages(orderPage.getTotalPages());
            
            log.info("获取用户订单列表成功 - 用户ID: {}, 订单数量: {}", userId, orders.size());
            return response;
            
        } catch (Exception e) {
            log.error("获取用户订单列表失败 - 用户ID: {}", userId, e);
            throw new RuntimeException("获取订单列表失败", e);
        }
    }

    @Override
    public OrderPageResponse getOrdersByUserIdAndStatus(Long userId, Integer status, Integer page, Integer size) {
        log.info("根据状态获取用户订单列表 - 用户ID: {}, 状态: {}, 页码: {}, 大小: {}", userId, status, page, size);
        
        try {
            // 创建分页参数
            Pageable pageable = PageRequest.of(page, size, Sort.by(Sort.Direction.DESC, "createdAt"));
            
            // 查询订单分页数据
            Page<Order> orderPage = orderRepository.findByUserIdAndStatus(userId, status, pageable);
            
            // 构建响应
            OrderPageResponse response = new OrderPageResponse();
            List<OrderResponse> orders = new ArrayList<>();
            
            // 转换订单数据
            for (Order order : orderPage.getContent()) {
                List<OrderItem> orderItems = orderItemRepository.findByOrderId(order.getId());
                OrderResponse orderResponse = convertToResponse(order, orderItems);
                orders.add(orderResponse);
            }
            
            response.setOrders(orders);
            response.setTotal(orderPage.getTotalElements());
            response.setPage(page);
            response.setSize(size);
            response.setTotalPages(orderPage.getTotalPages());
            
            log.info("根据状态获取用户订单列表成功 - 用户ID: {}, 状态: {}, 订单数量: {}", userId, status, orders.size());
            return response;
            
        } catch (Exception e) {
            log.error("根据状态获取用户订单列表失败 - 用户ID: {}, 状态: {}", userId, status, e);
            throw new RuntimeException("获取订单列表失败", e);
        }
    }

    @Override
    public OrderResponse updateOrderStatus(Long orderId, OrderUpdateStatusRequest updateRequest, Long userId) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public OrderResponse cancelOrder(Long orderId, Long userId) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public void deleteOrder(Long orderId, Long userId) {
        // TODO Auto-generated method stub
        
    }

    @Override
    public OrderResponse payOrder(Long orderId, Integer paymentMethod, Long userId) {
        log.info("支付订单 - 订单ID: {}, 用户ID: {}, 支付方式: {}", orderId, userId, paymentMethod);
        
        try {
            // 1. 查询订单
            Order order = orderRepository.findById(orderId)
                    .orElseThrow(() -> new RuntimeException("订单不存在"));
            
            // 2. 验证订单归属
            if (!order.getUserId().equals(userId)) {
                throw new RuntimeException("订单不属于当前用户");
            }
            
            // 3. 验证订单状态
            if (order.getStatus() != 0) { // 0-待付款
                throw new RuntimeException("订单状态不正确，无法支付");
            }
            
            // 4. 验证支付方式
            if (paymentMethod == null || paymentMethod < 1 || paymentMethod > 3) {
                throw new RuntimeException("支付方式不正确");
            }
            
            // 5. 模拟支付处理（实际项目中这里会调用第三方支付接口）
            log.info("开始处理支付 - 订单ID: {}, 支付方式: {}, 支付金额: {}", 
                    orderId, paymentMethod, order.getPayAmount());
            
            // 模拟支付延迟
            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
            
            // 6. 更新订单信息
            order.setStatus(1); // 1-待发货
            order.setPaymentMethod(paymentMethod);
            order.setPaymentTime(LocalDateTime.now());
            order.setUpdatedAt(LocalDateTime.now());
            
            // 7. 保存订单
            Order updatedOrder = orderRepository.save(order);
            
            // 8. 获取订单项
            List<OrderItem> orderItems = orderItemRepository.findByOrderId(orderId);
            
            log.info("支付成功 - 订单ID: {}, 支付方式: {}, 支付金额: {}", 
                    orderId, paymentMethod, order.getPayAmount());
            
            // 9. 返回响应
            OrderResponse response = convertToResponse(updatedOrder, orderItems);
            return response;
            
        } catch (RuntimeException e) {
            log.error("支付失败 - 订单ID: {}, 错误: {}", orderId, e.getMessage());
            throw e;
        } catch (Exception e) {
            log.error("支付异常 - 订单ID: {}, 错误: {}", orderId, e.getMessage(), e);
            throw new RuntimeException("支付处理失败", e);
        }
    }

    @Override
    public OrderPageResponse getAllOrders(Map<String, Object> params) {
        log.info("管理员获取所有订单列表 - 参数: {}", params);
        
        try {
            // 解析分页参数
            // 修复分页参数转换：处理字符串类型
            Integer page = 0;
            Object pageObj = params.get("page");
            if (pageObj != null) {
                try {
                    page = Integer.parseInt(pageObj.toString().trim());
                } catch (NumberFormatException e) {
                    log.warn("无效的页码参数: {}, 使用默认值0", pageObj);
                    page = 0;
                }
            }
            
            Integer size = 10;
            Object sizeObj = params.get("size");
            if (sizeObj != null) {
                try {
                    size = Integer.parseInt(sizeObj.toString().trim());
                } catch (NumberFormatException e) {
                    log.warn("无效的页面大小参数: {}, 使用默认值10", sizeObj);
                    size = 10;
                }
            }
            String keyword = (String) params.get("keyword");
            
            // 修复状态参数转换：处理空字符串情况
            Integer status = null;
            Object statusObj = params.get("status");
            if (statusObj != null && !statusObj.toString().trim().isEmpty()) {
                try {
                    status = Integer.parseInt(statusObj.toString().trim());
                } catch (NumberFormatException e) {
                    log.warn("无效的状态参数: {}, 将忽略状态过滤", statusObj);
                }
            }
            
            String startDate = (String) params.get("startDate");
            String endDate = (String) params.get("endDate");
            
            log.info("分页参数 - 页码: {}, 大小: {}, 关键词: {}, 状态: {}, 开始日期: {}, 结束日期: {}", 
                    page, size, keyword, status, startDate, endDate);
            
            // 创建分页参数
            Pageable pageable = PageRequest.of(page, size, Sort.by(Sort.Direction.DESC, "createdAt"));
            
            // 构建查询条件
            Page<Order> orderPage;
            if (status != null) {
                // 根据状态查询
                orderPage = orderRepository.findByStatus(status, pageable);
            } else {
                // 查询所有订单
                orderPage = orderRepository.findAll(pageable);
            }
            
            log.info("查询结果 - 总订单数: {}, 当前页订单数: {}", orderPage.getTotalElements(), orderPage.getContent().size());
            
            // 构建响应
            OrderPageResponse response = new OrderPageResponse();
            List<OrderResponse> orders = new ArrayList<>();
            
            // 转换订单数据
            for (Order order : orderPage.getContent()) {
                try {
                    List<OrderItem> orderItems = orderItemRepository.findByOrderId(order.getId());
                    OrderResponse orderResponse = convertToResponse(order, orderItems);
                    orders.add(orderResponse);
                } catch (Exception e) {
                    log.error("转换订单失败 - 订单ID: {}, 错误: {}", order.getId(), e.getMessage(), e);
                    // 继续处理其他订单，而不是完全失败
                }
            }
            
            response.setOrders(orders);
            response.setTotal(orderPage.getTotalElements());
            response.setPage(page);
            response.setSize(size);
            response.setTotalPages(orderPage.getTotalPages());
            
            log.info("管理员获取所有订单列表成功 - 订单数量: {}", orders.size());
            return response;
            
        } catch (Exception e) {
            log.error("管理员获取所有订单列表失败", e);
            throw new RuntimeException("获取订单列表失败", e);
        }
    }

    @Override
    public OrderResponse getOrderByIdForAdmin(Long orderId) {
        log.info("管理员获取订单详情 - 订单ID: {}", orderId);
        
        Order order = orderRepository.findById(orderId)
                .orElseThrow(() -> new RuntimeException("订单不存在"));
        
        // 获取订单项
        List<OrderItem> orderItems = orderItemRepository.findByOrderId(orderId);
        
        log.info("管理员订单查询成功 - 订单ID: {}", orderId);
        return convertToResponse(order, orderItems);
    }

    @Override
    public OrderResponse updateOrderStatusByAdmin(Long orderId, String status, String operator) {
        log.info("管理员更新订单状态 - 订单ID: {}, 新状态: {}, 操作员: {}", orderId, status, operator);
        
        try {
            // 1. 查询订单
            Order order = orderRepository.findById(orderId)
                    .orElseThrow(() -> new RuntimeException("订单不存在"));
            
            // 2. 验证状态转换的合法性
            Integer currentStatus = order.getStatus();
            Integer newStatus = parseStatus(status);
            
            if (newStatus == null) {
                throw new RuntimeException("无效的订单状态: " + status);
            }
            
            // 状态转换规则验证
            if (!isValidStatusTransition(currentStatus, newStatus)) {
                throw new RuntimeException(String.format("状态转换不合法: %s -> %s", 
                        getStatusText(currentStatus), getStatusText(newStatus)));
            }
            
            // 3. 更新订单状态
            order.setStatus(newStatus);
            order.setUpdatedAt(LocalDateTime.now());
            
            // 根据状态设置相应的时间字段
            if (newStatus == 2) { // 已发货
                order.setShippingTime(LocalDateTime.now());
            } else if (newStatus == 3) { // 已完成
                order.setCompletionTime(LocalDateTime.now());
            }
            
            orderRepository.save(order);
            log.info("订单状态更新成功 - 订单ID: {}, 旧状态: {}, 新状态: {}", 
                    orderId, currentStatus, newStatus);
            
            // 4. 获取订单项并返回响应
            List<OrderItem> orderItems = orderItemRepository.findByOrderId(orderId);
            return convertToResponse(order, orderItems);
            
        } catch (Exception e) {
            log.error("管理员更新订单状态失败 - 订单ID: {}, 错误: {}", orderId, e.getMessage(), e);
            throw new RuntimeException("更新订单状态失败: " + e.getMessage(), e);
        }
    }

    @Override
    public OrderResponse cancelOrderByAdmin(Long orderId, String reason, String operator) {
        log.info("管理员取消订单 - 订单ID: {}, 原因: {}, 操作员: {}", orderId, reason, operator);
        
        try {
            // 1. 查询订单
            Order order = orderRepository.findById(orderId)
                    .orElseThrow(() -> new RuntimeException("订单不存在"));
            
            // 2. 验证订单状态是否可以取消
            Integer currentStatus = order.getStatus();
            if (currentStatus != 0 && currentStatus != 1) { // 只能取消待付款和待发货的订单
                throw new RuntimeException(String.format("订单状态为%s，无法取消", getStatusText(currentStatus)));
            }
            
            // 3. 更新订单状态为已取消
            order.setStatus(4); // 4-已取消
            order.setUpdatedAt(LocalDateTime.now());
            
            // 记录取消原因到备注中
            String cancelInfo = String.format("管理员取消订单 - 操作员: %s, 原因: %s, 时间: %s", 
                    operator, reason, LocalDateTime.now());
            String currentRemark = order.getRemark() != null ? order.getRemark() : "";
            order.setRemark(currentRemark + "\n" + cancelInfo);
            
            orderRepository.save(order);
            log.info("订单取消成功 - 订单ID: {}, 旧状态: {}, 新状态: 已取消", orderId, currentStatus);
            
            // 4. 获取订单项并返回响应
            List<OrderItem> orderItems = orderItemRepository.findByOrderId(orderId);
            return convertToResponse(order, orderItems);
            
        } catch (Exception e) {
            log.error("管理员取消订单失败 - 订单ID: {}, 错误: {}", orderId, e.getMessage(), e);
            throw new RuntimeException("取消订单失败: " + e.getMessage(), e);
        }
    }

    @Override
    public OrderStatsResponse getOrderStats() {
        log.info("开始获取订单统计信息");
        
        try {
            // 获取当前时间
            LocalDateTime now = LocalDateTime.now();
            LocalDateTime todayStart = now.withHour(0).withMinute(0).withSecond(0).withNano(0);
            LocalDateTime todayEnd = now.withHour(23).withMinute(59).withSecond(59).withNano(999999999);
            
            // 统计总订单数
            long totalOrders = orderRepository.count();
            log.info("总订单数: {}", totalOrders);
            
            // 统计今日订单数
            long todayOrders = orderRepository.countByCreatedAtBetween(todayStart, todayEnd);
            log.info("今日订单数: {}", todayOrders);
            
            // 统计总销售额（已完成订单）
            BigDecimal totalSales = orderRepository.sumTotalAmountByStatus(3); // 3-已完成
            log.info("总销售额: {}", totalSales);
            
            // 统计今日销售额（已完成订单）
            BigDecimal todaySales = orderRepository.sumTotalAmountByStatusAndCreatedAtBetween(3, todayStart, todayEnd);
            log.info("今日销售额: {}", todaySales);
            
            // 统计各状态订单数
            long pendingOrders = orderRepository.countByStatus(0); // 0-待付款
            long paidOrders = orderRepository.countByStatus(1);    // 1-待发货
            long shippedOrders = orderRepository.countByStatus(2); // 2-已发货
            long completedOrders = orderRepository.countByStatus(3); // 3-已完成
            long cancelledOrders = orderRepository.countByStatus(4); // 4-已取消
            
            log.info("各状态订单数 - 待付款: {}, 已付款: {}, 已发货: {}, 已完成: {}, 已取消: {}", 
                    pendingOrders, paidOrders, shippedOrders, completedOrders, cancelledOrders);
            
            // 构建响应
            OrderStatsResponse stats = new OrderStatsResponse();
            stats.setTotalOrders(totalOrders);
            stats.setTodayOrders(todayOrders);
            stats.setTotalSales(totalSales != null ? totalSales : BigDecimal.ZERO);
            stats.setTodaySales(todaySales != null ? todaySales : BigDecimal.ZERO);
            stats.setPendingOrders(pendingOrders);
            stats.setPaidOrders(paidOrders);
            stats.setShippedOrders(shippedOrders);
            stats.setCompletedOrders(completedOrders);
            stats.setCancelledOrders(cancelledOrders);
            
            log.info("订单统计信息获取成功: {}", stats);
            return stats;
            
        } catch (Exception e) {
            log.error("获取订单统计信息失败", e);
            throw new RuntimeException("获取订单统计失败", e);
        }
    }

    /**
     * 将订单实体转换为响应DTO
     */
    private OrderResponse convertToResponse(Order order, List<OrderItem> orderItems) {
        OrderResponse response = new OrderResponse();
        response.setId(order.getId());
        response.setOrderNo(order.getOrderNo());
        response.setUserId(order.getUserId());
        response.setUsername(order.getUsername());
        response.setTotalAmount(order.getTotalAmount());
        response.setShippingFee(order.getShippingFee());
        response.setPayAmount(order.getPayAmount());
        response.setStatus(order.getStatus());
        response.setStatusText(getStatusText(order.getStatus()));
        response.setPaymentMethod(order.getPaymentMethod());
        response.setPaymentMethodText(getPaymentMethodText(order.getPaymentMethod()));
        response.setPaymentTime(order.getPaymentTime());
        response.setShippingTime(order.getShippingTime());
        response.setCompletionTime(order.getCompletionTime());
        response.setReceiverName(order.getReceiverName());
        response.setReceiverPhone(order.getReceiverPhone());
        response.setReceiverAddress(order.getReceiverAddress());
        response.setRemark(order.getRemark());
        response.setCreatedAt(order.getCreatedAt());
        response.setUpdatedAt(order.getUpdatedAt());

        // 转换订单项
        List<OrderItemResponse> itemResponses = orderItems.stream()
                .map(this::convertItemToResponse)
                .collect(Collectors.toList());
        response.setItems(itemResponses);

        return response;
    }

    /**
     * 将订单项实体转换为响应DTO
     */
    private OrderItemResponse convertItemToResponse(OrderItem item) {
        OrderItemResponse response = new OrderItemResponse();
        response.setId(item.getId());
        response.setOrderId(item.getOrderId());
        response.setProductId(item.getProductId());
        response.setProductName(item.getProductName());
        response.setProductImage(item.getProductImage());
        response.setProductPrice(item.getProductPrice());
        response.setQuantity(item.getQuantity());
        response.setSubtotal(item.getSubtotal());
        return response;
    }

    /**
     * 获取订单状态文本
     */
    private String getStatusText(Integer status) {
        if (status == null) return "未知";
        switch (status) {
            case 0: return "待付款";
            case 1: return "待发货";
            case 2: return "已发货";
            case 3: return "已完成";
            case 4: return "已取消";
            case 5: return "退款中";
            case 6: return "已退款";
            default: return "未知";
        }
    }

    /**
     * 获取支付方式文本
     */
    private String getPaymentMethodText(Integer paymentMethod) {
        if (paymentMethod == null) return "未知";
        switch (paymentMethod) {
            case 1: return "微信支付";
            case 2: return "支付宝";
            case 3: return "银行卡";
            default: return "未知";
        }
    }

    /**
     * 生成订单编号
     */
    private String generateOrderNo() {
        return "ORD" + System.currentTimeMillis() + (int)(Math.random() * 1000);
    }

    /**
     * 解析状态字符串为整数
     */
    private Integer parseStatus(String status) {
        if (status == null) return null;
        try {
            return Integer.parseInt(status);
        } catch (NumberFormatException e) {
            return null;
        }
    }

    /**
     * 验证状态转换是否合法
     */
    private boolean isValidStatusTransition(Integer currentStatus, Integer newStatus) {
        if (currentStatus == null || newStatus == null) return false;
        
        // 相同状态允许
        if (currentStatus.equals(newStatus)) return true;
        
        // 状态转换规则
        switch (currentStatus) {
            case 0: // 待付款
                // 待付款可以转为：已取消(4)、待发货(1)
                return newStatus == 4 || newStatus == 1;
            case 1: // 待发货
                // 待发货可以转为：已发货(2)、已取消(4)
                return newStatus == 2 || newStatus == 4;
            case 2: // 已发货
                // 已发货可以转为：已完成(3)
                return newStatus == 3;
            case 3: // 已完成
                // 已完成不能转为其他状态
                return false;
            case 4: // 已取消
                // 已取消不能转为其他状态
                return false;
            default:
                return false;
        }
    }

    /**
     * 获取当前用户的token
     */
    private String getCurrentToken() {
        // 从请求头中获取Authorization
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (attributes != null) {
            HttpServletRequest request = attributes.getRequest();
            String authorization = request.getHeader("Authorization");
            if (authorization != null && authorization.startsWith("Bearer ")) {
                return authorization.substring(7); // 去掉"Bearer "前缀
            }
        }
        // 如果没有token，返回空字符串
        return "";
    }

    /**
     * 从JSON节点安全获取文本值
     */
    private String getJsonNodeText(JsonNode node, String fieldName) {
        try {
            if (node != null && node.has(fieldName)) {
                JsonNode fieldNode = node.get(fieldName);
                if (fieldNode != null && !fieldNode.isNull()) {
                    return fieldNode.asText();
                }
            }
        } catch (Exception e) {
            log.warn("获取JSON字段 {} 失败: {}", fieldName, e.getMessage());
        }
        return null;
    }
}